package com.example.plugin.hook;

import android.content.ComponentName;
import android.content.Intent;
import android.util.Log;

import com.example.plugin.AMSHookHelper;
import com.example.plugin.StubActivity;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * author: zhouyh
 * created on: 2/2/21 11:52 AM
 * description:IActivityManager动态代理
 */
public class IActivityManagerHandler implements InvocationHandler {

    private static final String TAG = "IActivityManagerHandler";

    private Object base;

    public IActivityManagerHandler(Object rawActivityManager) {
        this.base = rawActivityManager;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        Log.e("m1:",method.getName());
        //指接
        if ("startActivity".equals(method.getName())){
            Log.i(TAG,"hello ,you are hooking startActivity");
            Intent raw = null;
            int index = 0;
            for (int i = 0; i < args.length; i++){
                if (args[i] instanceof Intent){
                    index = i;
                    break;
                }
            }
            raw = (Intent) args[index];
            Intent target = new Intent();
            // 这里包名直接写死,如果再插件里,不同的插件有不同的包  传递插件的包名即可
            String packageName = "com.example.plugin";
            // 这里我们把启动的Activity临时替换为 StubActivity
            ComponentName componentName = new ComponentName(packageName, StubActivity.class.getCanonicalName());
            target.setComponent(componentName);

            // 把我们原始要启动的TargetActivity先存起来
            target.putExtra(AMSHookHelper.EXTRA_TARGET_INTENT,raw);
            // 替换掉Intent, 达到欺骗AMS的目的
            args[index] = target;
            Log.d(TAG, "hook success");
            return method.invoke(base, args);
        }

        return method.invoke(base,args);

    }
}
